package com.dearbinge.opentapi.content.user;

import com.dearbinge.data.api.im.UserContactService;
import com.dearbinge.data.api.thumbs.ThumbsService;
import com.dearbinge.data.api.user.UserService;
import com.dearbinge.data.api.userSolicitude.UserSolicitudeService;
import com.dearbinge.data.pojo.user.User;
import com.dearbinge.data.redis.service.RedisService;
import com.dearbinge.utils.PageResult;
import com.dearbinge.utils.ResultMsg;
import com.dearbinge.utils.age.AgeUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(description = "用户接口")
@RestController
@CrossOrigin
@RequestMapping("/user")
@EnableAutoConfiguration
public class UserController extends WebMvcConfigurerAdapter {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisService redisService;

    @Autowired
    private UserSolicitudeService userSolicitudeService;

    @Autowired
    private UserContactService userContactService;

    @Autowired
    private ThumbsService thumbsService;

/*    @Autowired
    private OfUserService ofUserService;*/


    /**
     * 新增用户/修改用户
     */
    @ApiOperation(value = "新增/修改用户",notes = "新增/修改用户")
    @RequestMapping(value = "/addOrUpdate",method = RequestMethod.POST)
    public ResultMsg<String> addOrUpdate(@RequestBody User user){
        Integer dataCode = 0;
        try {
            if (user != null && user.getDateOfBirth() != null){
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                Date date = format.parse(user.getDateOfBirth());
                int age = AgeUtil.getAgeByBirth(date);
                user.setAge(age);
            }
            if (user.getId() != null && user.getId() != 0 ){
                dataCode = userService.update(user);
                if (dataCode > 0){
                    return ResultMsg.ok("修改成功");
                }
            }else {
                dataCode = userService.insert(user);
                if (dataCode != null){
                    /*Ofuser ofuser = new Ofuser();
                    ofuser.setUsername(dataCode.toString());
                    ofuser.setPlainpassword("123456");
                    ofuser.setName(dataCode.toString());
                    ofUserService.insert(ofuser);*/
                    return ResultMsg.ok("添加成功");
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return ResultMsg.error(500,"系统异常");
    }


    /**
     * 删除用户
     */
    @ApiOperation(value = "删除用户",notes = "删除用户")
    @ApiImplicitParam(name = "id",value = "id",paramType = "query")
    @RequestMapping(value = "/delete",method = RequestMethod.GET)
    private ResultMsg<String> delete(Integer id){
        Integer dataCode = 0;
        try {
            dataCode = userService.delete(id);
            if (dataCode > 0){
                return ResultMsg.ok("删除成功");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return ResultMsg.error(500,"系统异常");
    }

    /**
     * 根据ID查询用户
     */
    @ApiOperation(value = "根据ID查询用户",notes = "根据ID查询用户")
    @ApiImplicitParam(name = "id",value = "id",paramType = "query")
    @RequestMapping(value = "/getById",method = RequestMethod.GET)
    private ResultMsg<User> getById(Integer id){
        try {
            User user = userService.getById(id,1);
            if (user != null) {
                user = count(user);
            }
            return ResultMsg.ok(user);
        }catch (Exception e){
            e.printStackTrace();
        }
        return ResultMsg.error(500,"系统异常");
    }

    /**
     * 用户根据个人ID查询信息
     */
    @ApiOperation(value = "用户根据个人ID查询信息",notes = "用户根据个人ID查询信息")
    @ApiImplicitParam(name = "id",value = "id",paramType = "query")
    @RequestMapping(value = "/getMeById",method = RequestMethod.GET)
    private ResultMsg<User> getMeById(Integer id){
        try {
            User user = userService.getById(id,0);
            if (user != null) {
                user = count(user);
            }
            return ResultMsg.ok(user);
        }catch (Exception e){
            e.printStackTrace();
        }
        return ResultMsg.error(500,"系统异常");
    }

    private User count(User user) {
        Integer thumbsCount = thumbsService.getCountBeLiked(user.getId());
        Integer fansCount = userSolicitudeService.getCountBeConcerned(user.getId());
        Integer focusCount = userSolicitudeService.count(user.getId());
        user.setThumbsCount(thumbsCount.toString());
        user.setFansCount(fansCount.toString());
        user.setFocusCount(focusCount.toString());
        return user;
    }


    /**
     * 查询在线用户
     */
    @ApiOperation(value = "查询在线用户",notes = "查询在线用户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId",value = "当前用户ID",paramType = "query"),
            @ApiImplicitParam(name = "compositor",value = "排序（0：最近活跃  1：离我最近）",paramType = "query"),
            @ApiImplicitParam(name = "sex",value = "性別（1：男   0：女）",paramType = "query"),
            @ApiImplicitParam(name = "type",value = "类型（1：商家   0：买家）",paramType = "query"),
            @ApiImplicitParam(name = "district",value = "地区",paramType = "query"),
            @ApiImplicitParam(name = "staAge",value = "起始年龄",paramType = "query"),
            @ApiImplicitParam(name = "endAge",value = "结束年龄",paramType = "query"),
            @ApiImplicitParam(name = "weight",value = "体重",paramType = "query"),
            @ApiImplicitParam(name = "stature",value = "身高",paramType = "query"),
            @ApiImplicitParam(name = "emotionalState",value = "感情状态",paramType = "query"),
            @ApiImplicitParam(name = "lon",value = "经度",paramType = "query"),
            @ApiImplicitParam(name = "lat",value = "纬度",paramType = "query"),
            @ApiImplicitParam(name = "raidus",value = "范围（米为单位）",paramType = "query"),
            @ApiImplicitParam(name = "pageNo",value = "当前页",paramType = "query"),
            @ApiImplicitParam(name = "pageSize",value = "页面数量",paramType = "query")})
    @RequestMapping(value = "getOnLineUser ",method = RequestMethod.GET)
    public PageResult<List<Map<String,Object>>> getOnLineUser(Integer compositor,Integer type,String district,String userId,Integer pageNo, Integer pageSize,
                                                              Double lon, Double lat, Integer raidus,
                                                              Integer sex,Integer staAge,Integer endAge,String weight,
                                                              String stature,Integer emotionalState){
        PageResult<List<Map<String,Object>>> pageResult = new PageResult<>();
        try {
            weight = StringUtils.isEmpty(weight) ? null : weight;
            stature = StringUtils.isEmpty(stature) ? null : stature;
            Double minLat = null;
            Double maxLat = null;
            Double minLng = null;
            Double maxLng = null;
            Double latitude = lat;
            Double longitude = lon;
            if(raidus != null && raidus != 0 && lon != null && lon != 0 && lat != null && lat != 0 ){
                // 赤道周长24901英里 1609是转换成米的系数
                Double degree = (24901 * 1609) / 360.0;
                double raidusMile = raidus;

                Double dpmLat = 1 / degree;
                Double radiusLat = dpmLat * raidusMile;
                minLat = latitude - radiusLat;
                maxLat = latitude + radiusLat;

                Double mpdLng = degree * Math.cos(latitude * (Math.PI / 180));
                Double dpmLng = 1 / mpdLng;
                Double radiusLng = dpmLng * raidusMile;
                minLng = longitude - radiusLng;
                maxLng = longitude + radiusLng;
            }
            /*if (raidus != null){
                User userById = userService.getUserById(Integer.parseInt(userId));
                if (userById != null && userById.getCertified() == null || userById.getCertified() != true){
//                    return PageResult.error(505,"您还不是尊贵VIP，不能根据距离筛选用户，谢谢！");
                    return PageResult.error(505,"您还沒实名验证，不能根据距离筛选用户，请先通过实名验证");
                }
            }*/
            Boolean sexx = null;
            if (sex != null){
                if (sex == 1){
                    sexx = true;
                }else {
                    sexx = false;
                }
            }
            pageResult = userService.getOnLineUser(compositor,type,district,staAge,endAge,weight,stature,emotionalState,sexx,minLat,minLng,maxLat,maxLng,longitude,latitude,pageNo,pageSize);
        }catch (Exception e){
            e.printStackTrace();
        }
        return pageResult;
    }

    /**
     * 用户绑定手机号码
     */
    @ApiOperation(value = "用户绑定手机号码",notes = "用户绑定手机号码")
    @ApiImplicitParams({@ApiImplicitParam(name = "userId",value = "用户ID",paramType = "query"),
            @ApiImplicitParam(name = "phone",value = "手机号码",paramType = "query"),
            @ApiImplicitParam(name = "smsCode",value = "验证码",paramType = "query")})
    @RequestMapping(value = "/bindingPhone",method = RequestMethod.GET)
    public ResultMsg<String> bindingPhone(String userId,String phone,String smsCode){
        try {
            String co = phone +"smsCode";
            String code = redisService.get(co);
            if (!code.equals(smsCode)){
                return ResultMsg.error(500,"验证码错误！");
            }
            Integer dataCode = userService.bindingPhone(userId,phone);
            if (dataCode > 0){
                return ResultMsg.ok("绑定成功！");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return ResultMsg.error(500,"系统异常");
    }

    /**
     * 用户注册接口
     */
    @ApiOperation(value = "用户注册接口",notes = "用户注册接口")
    @ApiImplicitParams({@ApiImplicitParam(name = "userName",value = "用户名",paramType = "query")
            ,@ApiImplicitParam(name = "pwd",value = "密码",paramType = "query")})
    @RequestMapping(value = "/register",method = RequestMethod.GET)
    public ResultMsg<String> register(String userName,String pwd){
        try {
            Integer dataCode = userService.register(userName,pwd);
            if (dataCode > 0){
                return ResultMsg.ok("注冊成功");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return ResultMsg.error(500,"系统异常");
    }

    /**
     * 根据用户名查看校验该用户名是否存在
     */
    @ApiOperation(value = "根据用户名查看校验该用户名是否存在",notes = "根据用户名查看校验该用户名是否存在")
    @ApiImplicitParam(name = "userName",value = "用户名",paramType = "query")
    @RequestMapping(value = "/checkout ",method = RequestMethod.GET)
    public ResultMsg<String> checkout(String userName){
        try {
            Integer id = userService.checkout(userName);
            if (id != null){
                return ResultMsg.error(505,"用户名已存在，请重新输入！");
            }
            return ResultMsg.ok("用户名可用！");
        }catch (Exception e){
            e.printStackTrace();
        }
        return ResultMsg.error(500,"系统异常");
    }

    /**
     * 用户登录接口
     */
    @ApiOperation(value = "用户登录",notes = "用户登录")
    @ApiImplicitParams({@ApiImplicitParam(name = "userName",value = "用户名",paramType = "query"),
            @ApiImplicitParam(name = "pwd",value = "用户密码",paramType = "query")})
    @RequestMapping(value = "/login",method = RequestMethod.GET)
    public ResultMsg<String> login(String userName,String pwd){
        try {
            Integer id = userService.login(userName,pwd);
            if (id != null){
                return ResultMsg.ok(id.toString());
            }else{
                return ResultMsg.error(505,"用户名或者密码错误，请重新输入登录！");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return ResultMsg.error(500,"系统异常");
    }


    /**
     * 根据该用户ID与对方用户ID
     */
    @ApiOperation(value = "根据该用户ID与对方用户ID",notes = "根据该用户ID与对方用户ID")
    @ApiImplicitParams({@ApiImplicitParam(name = "userId",value = "该用户ID",paramType = "query"),
            @ApiImplicitParam(name = "solicitudeId",value = "对方用户ID",paramType = "query")})
    @RequestMapping(value = "/getIsSolicitude",method = RequestMethod.GET)
    public ResultMsg<Map<String,Object>> getIsSolicitude(String userId,String solicitudeId){
        try {
            String soId =  userSolicitudeService.getIsSolicitude(userId,solicitudeId);
            String frllowId = userContactService.getIsHailFellow(userId,solicitudeId);
            Map<String,Object> map = new HashMap<String,Object>();
            map.put("soId",soId);
            map.put("frllowId",frllowId);
            return ResultMsg.ok(map);
        }catch (Exception e){
            e.printStackTrace();
        }
        return ResultMsg.error(500,"系统异常");
    }


}
